export class WebSocketService {
  constructor(config) {
    this.ws = null
    this.config = {
      reconnectTimeout: 3000,
      maxReconnectAttempts: 5,
      ...config
    }
    this.reconnectCount = 0
    this.reconnectTimer = null
    this.messageHandlers = new Map()
  }

  connect() {
    try {
      this.ws = new WebSocket(this.config.url)
      this.bindEvents()
    } catch (error) {
      console.error('WebSocket 连接错误:', error)
      this.reconnect()
    }
  }

  bindEvents() {
    if (!this.ws) return

    this.ws.onopen = () => {
      console.log('WebSocket 连接成功')
      this.reconnectCount = 0
    }

    this.ws.onmessage = (event) => {
      console.log(event)
      try {
        const data = JSON.parse(event.data)
        this.handleMessage(data)
      } catch (error) {
        console.error('WebSocket 消息解析错误:', error)
      }
    }

    this.ws.onclose = () => {
      console.log('WebSocket 连接关闭')
      this.reconnect()
    }

    this.ws.onerror = (error) => {
      console.error('WebSocket 错误:', error)
      this.ws?.close()
    }
  }

  reconnect() {
    if (this.reconnectCount >= this.config.maxReconnectAttempts) {
      console.error('WebSocket 重连次数超过最大限制')
      return
    }

    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
    }

    this.reconnectTimer = setTimeout(() => {
      console.log(`WebSocket 第 ${this.reconnectCount + 1} 次重连...`)
      this.reconnectCount++
      this.connect()
    }, this.config.reconnectTimeout)
  }

  subscribe(type, handler) {
    if (!this.messageHandlers.has(type)) {
      this.messageHandlers.set(type, new Set())
    }
    this.messageHandlers.get(type).add(handler)

    // 返回取消订阅函数
    return () => {
      this.messageHandlers.get(type)?.delete(handler)
    }
  }

  handleMessage(data) {
    console.log(data)
    const handlers = this.messageHandlers.get(data.type)
    handlers?.forEach((handler) => handler(data.data))

    /**
     * 因为在ws-types中注册了all类型，在页面使用的地方registerHandlers中
     * 也添加了对应all的事件处理方法（HomeView页面），所以此处不再需要单独处理
     * data.type == all时再去调用所有的messageHandlers，
     * 否则会造成数据二次请求
     */
    // 处理全局消息
    // if (data.type === 'all') {
    //   this.messageHandlers.forEach((handlers) => {
    //     handlers.forEach((handler) => handler(data.data))
    //   })
    // }
  }

  disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
      this.reconnectTimer = null
    }
    this.messageHandlers.clear()
  }
}
